﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PegasCompany.Data
{
    public partial class SiteMenuItem
    {
        public static List<SiteMenuItem> GetMenuItems(string sRequestFilePath)
        {
            var parentMenuItem = Search(new SiteMenuItem
            {
                Url = sRequestFilePath
            }).FirstOrDefault();

            if (parentMenuItem != null)
            {
                if (parentMenuItem.Id != null)
                {
                    return GetMenuItems(parentMenuItem.Id.Value);
                }
            }
            return null;
        }

        public static List<SiteMenuItem> GetMenuItems(int iParentSiteMenuItemId)
        {
            List<SiteMenuItem> lstMenuItems = Search();
            return lstMenuItems.Where(item => item.ParentSiteMenuItemId == iParentSiteMenuItemId).ToList();
        }

        public static List<SiteMenuItem> GetMenuItemsTree(bool bIsAdminAccess)
        {
            List<SiteMenuItem> lstMenuItems;

            if (bIsAdminAccess)
            {
                lstMenuItems = Search();
            }
            else
            {
                lstMenuItems = Search(
                        new SiteMenuItem
                        {
                            IsAdmin = false
                        }
                    );
            }

            List<SiteMenuItem> lstMenuItemsTree = new List<SiteMenuItem>();
            foreach (SiteMenuItem smi in lstMenuItems)
            {
                if (smi.ParentSiteMenuItemId == null)
                {
                    lstMenuItemsTree.Add(smi);
                }
                else
                {
                    var parent = lstMenuItemsTree.SingleOrDefault(pi => pi.Id == smi.ParentSiteMenuItemId);
                    if (parent != null)
                    {
                        parent.Childs.Add(smi);
                    }
                    else
                    {
                        foreach (SiteMenuItem item in lstMenuItemsTree)
                        {
                            if (item.Childs != null)
                            {
                                var subParent = item.Childs.SingleOrDefault(pi => pi.Id == smi.ParentSiteMenuItemId);
                                if (subParent != null)
                                {
                                    subParent.Childs.Add(smi);
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            return lstMenuItemsTree;
        }
    }
}
